package com.demo.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.demo.model.UserContext;
import com.demo.model.UserDto;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * @author Administrator
 * @version 1.0
 **/
@Slf4j
@Component
public class AuthFilter extends ZuulFilter {

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public Object run() throws ZuulException {
        log.info("--------> AuthFilter");
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        //从安全上下文中拿 到用户身份对象
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(!(authentication instanceof OAuth2Authentication)){
            return null;
        }

        String authorization = request.getHeader("Authorization");
        Jwt token = JwtHelper.decode(authorization.substring("bearer ".length()));
        JSONObject claimsJson = JSON.parseObject(token.getClaims());

        UserDto userDto = new UserDto();
        userDto.setId(claimsJson.getString("id"));
        userDto.setUsername(claimsJson.getString("name"));
        userDto.setDepartName(claimsJson.getString("departName"));
        userDto.setRole(claimsJson.getString("role"));

        //把身份信息和权限信息放在json中，加入http的header中,转发给微服务
        String encodeToString = Base64.getEncoder().encodeToString(JSON.toJSONString(userDto).getBytes(StandardCharsets.UTF_8));
        ctx.addZuulRequestHeader(UserContext.KEY_USERINFO_IN_HTTP_HEADER, encodeToString);


        return null;
    }
}
